package org.bing.engine.console.service;

import java.util.List;

import org.bing.engine.core.domain.ControllerGroup;

public class ControllerGroupManager extends AbstractHibernateManager {

    private LevelCodeManager levelCodeManager = new LevelCodeManager();

    public void save(ControllerGroup group) {
        String code = findWellCode(group);
        group.setCode(code);
        if (group.getId() <= 0) {
            logger.info("New controller group " + group);
        }
        template.saveOrUpdate(group);
    }

    public void delete(String code) {
        String prefix = levelCodeManager.calcPrefixCode(code);
        super.excuteHql("delete from ControllerGroup g where g.code like ? ", new Object[] { prefix + "%" });
    }

    @SuppressWarnings("unchecked")
    public List<ControllerGroup> findAll() {
        List<ControllerGroup> list = template.find("select g from ControllerGroup g order by g.code");
        return list;
    }

    @SuppressWarnings("unchecked")
    public List<ControllerGroup> findByParent(ControllerGroup parent) { 
        if (parent == null) {
            List<ControllerGroup> list = template.find("select g from ControllerGroup g where g.parent is null");
            return list;
        } else {
            List<ControllerGroup> list = template.find("select g from ControllerGroup g where g.parent = ?", parent);
            return list;
        }
    }

    /** TODO impl find free code */
    private String findWellCode(ControllerGroup group) {
        ControllerGroup parent = group.getParent();
        String maxCode = null;
        if (parent == null) {
            maxCode = super.findUniqueString("select max(g.code) from ControllerGroup g where g.parent is null", null);
        } else {
            maxCode = super.findUniqueString("select max(g.code) from ControllerGroup g where g.parent = ?", new Object[] { parent });
        }
        if (maxCode == null && parent == null) { // global first code
            return levelCodeManager.getFirstCode();
        }
        return maxCode == null ? levelCodeManager.calcFirstChild(parent.getCode()) : levelCodeManager.calcNext(maxCode);
    }

}
